package http

import (
	"bytes"
	"io"
	"io/ioutil"
	"net/http"
	"round_game/common/json"
)

func RequestHttp(url, method string, req interface{}, res interface{}) (status int, err error) {
	param, err := json.Marshal(req)
	if err != nil {
		return 0, err
	}
	status, data, err := Request(url, param, method)
	if err != nil {
		return status, err
	}

	return status, json.Unmarshal(data, res)
}

//Request do method & recieve data
func Request(url string, param []byte, method string) (status int, ret []byte, err error) {
	req, err := CreateJSONRequest(url, bytes.NewBuffer(param), method)
	if err != nil {
		return
	}
	ret, status, err = DoRequest(req, false)
	return
}

//CreateJSONRequest return a json http.Request
func CreateJSONRequest(url string, body io.Reader, method string) (req *http.Request, err error) {
	req, err = http.NewRequest(method, url, body)
	if err != nil {
		return
	}
	req.Header.Add("Content-Type", "application/json")
	return
}

//DoRequest send request & recieve response
func DoRequest(req *http.Request, ignoreBody bool) (ret []byte, status int, err error) {
	client := http.Client{}
	res, err := client.Do(req)
	if err != nil {
		return
	}
	defer res.Body.Close()
	status = res.StatusCode
	if ignoreBody {
		return
	}
	ret, err = ioutil.ReadAll(res.Body)
	return
}
